﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Josn.Net序列化
{
    /// <summary>
    /// 引用Newtonsoft.Jon 插件
    /// </summary>
    public class Program
    {
        static void Main(string[] args)
        {
            ///序列化
            List<Person> p = Seed();
            string Json = GetJosn<Person>(p);
            //反序列化为List<T>
            List<Person> p2 = GetList<Person>(Json);

            DataTable dt = GetTable(Json);

            Console.ReadKey();


        }


        /// <summary>
        /// 实体类型
        /// </summary>
        public class Person
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Sex { get; set; }
            public DateTime Birthday { get; set; }
            public DateTime InputTime { get; set; }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <returns></returns>
        public static List<Person> Seed()
        {
            List<Person> persons = new List<Person>() {
                new Person() { Id=1, Name="张三", Sex="男", Birthday=DateTime.Now.AddYears(-19), InputTime=DateTime.Now },
                new Person() { Id=2, Name="小红", Sex="女", Birthday=DateTime.Now.AddYears(-20), InputTime=DateTime.Now }
            };
            return persons;
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T">泛型实体</typeparam>
        /// <param name="List">数据源</param>
        /// <returns>Json数据</returns>
        public static string GetJosn<T>(List<T> List)
        {
            IsoDateTimeConverter TimeFormat = new IsoDateTimeConverter();
            TimeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string Result = JsonConvert.SerializeObject(List, TimeFormat);
            return Result;
        }

        /// <summary>
        /// 反序列化为List<T>
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static List<T> GetList<T>(string Json) where T : class
        {
            List<T> list = new List<T>();
            object o = JsonConvert.DeserializeObject(Json, typeof(List<T>));
            return o as List<T>;
        }

        /// <summary>
        /// 反序列化为DataTable
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static DataTable GetTable(string Json)
        {
            DataTable dt = JsonConvert.DeserializeObject<DataTable>(Json);
            return dt;
        }

    }
}
